package com.company.workflow.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.workflow.mapper.ProcessTemplateMapper;
import com.company.workflow.model.ProcessTemplate;
import com.company.workflow.service.ProcessTemplateService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ProcessTemplateServiceImpl extends ServiceImpl<ProcessTemplateMapper, ProcessTemplate> implements ProcessTemplateService {

    @Autowired
    private RepositoryService repositoryService;

    @Override
    @Transactional
    public ProcessTemplate saveTemplate(ProcessTemplate template) {
        if (template.getId() == null) {
            template.setCreateTime(LocalDateTime.now());
            template.setVersion(1);
            template.setStatus("DRAFT");
        }
        template.setUpdateTime(LocalDateTime.now());
        saveOrUpdate(template);
        return template;
    }

    @Override
    public ProcessTemplate getTemplate(Long id) {
        return getById(id);
    }

    @Override
    public List<ProcessTemplate> listTemplates() {
        return list();
    }

    @Override
    @Transactional
    public void deleteTemplate(Long id) {
        ProcessTemplate template = getById(id);
        if (template != null) {
            // 如果流程已部署，需要先删除部署
            if ("DEPLOYED".equals(template.getStatus())) {
                repositoryService.deleteDeployment(template.getKey(), true);
            }
            removeById(id);
        }
    }

    @Override
    @Transactional
    public String deployTemplate(Long id) {
        ProcessTemplate template = getById(id);
        if (template == null) {
            throw new RuntimeException("流程模板不存在");
        }
        
        // 部署流程
        Deployment deployment = repositoryService.createDeployment()
                .name(template.getName())
                .key(template.getKey())
                .addString(template.getKey() + ".bpmn20.xml", template.getXmlContent())
                .deploy();

        // 更新模板状态
        template.setStatus("DEPLOYED");
        template.setUpdateTime(LocalDateTime.now());
        updateById(template);

        return deployment.getId();
    }
} 